package com.hliushi.demo.serivce;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author llhuang10
 * @date 2021/7/22 21:17
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Resource
    private PasswordEncoder pw;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.warn("执行了loadUserByUsername方法");

        // 1.查询数据库判断用户是否存在, 如果不存在就会抛出UsernameNotFoundException
        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        // 2.把查询出来的密码 (注册时已经被加密过) 进行解析, 或者直接把密码放入构造方法
        // String password = pw.encode("123456");
        String password = "123456";

        //
        return new User(username, password, AuthorityUtils
                .commaSeparatedStringToAuthorityList("admin,normal"));
    }
}
